package com.dson.code.service.impl;

import com.dson.code.pojo.AuthCode;
import com.dson.code.repository.AuthCodeRepository;
import com.dson.common.service.AuthCodeService;
import com.dson.common.service.EmailService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import java.util.Collections;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;

@Service
public class AuthCodeServiceImpl implements AuthCodeService {
    private static final int AUTH_CODE_LENGTH = 6;

    @Autowired
    private AuthCodeRepository authCodeRepository;

    @Reference(timeout = 20000)
    private EmailService emailService;

    @Override
    public Boolean sendCode(String email) {
        Date now = new Date();
        String code = generateCode();

        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        authCode.setCreateTime(now);
        authCode.setExpireTime(new DateTime(now).plusMinutes(10).toDate());
        authCodeRepository.save(authCode);
        return emailService.sendEmail(email, code);
    }

    @Override
    public Integer checkCode(String email, String code) {
        Page<AuthCode> authCodePage = authCodeRepository.getByEmailOrderByCreateTimeDesc(
                email, PageRequest.of(0, 1));
        AuthCode authCode = Optional.ofNullable(authCodePage)
                .map(Page::getContent)
                .orElse(Collections.emptyList())
                .stream()
                .findFirst()
                .orElse(null);
        if (authCode != null && Objects.equals(authCode.getCode(), code)) {
            if (authCode.getExpireTime().before(new Date())) {
                return 2;
            }
            return 0;
        }
        return 1;
    }

    private String generateCode() {
        return RandomStringUtils.randomNumeric(AUTH_CODE_LENGTH);
    }
}
